package com.rjpacket.supernews.app.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

/**
 * Created by aaa on 15-3-11.
 */
public class ImageLoader extends AsyncTask<String, Integer, byte[]> {
    private ImageView imageView;
    private String imgUrl;

    public ImageLoader(ImageView imageView) {
        this.imageView = imageView;
    }

    @Override
    protected byte[] doInBackground(String... params) {
        byte[] bytes = new byte[0];

        if (params != null && params.length > 0) {
            imgUrl = params[0];

            bytes = HttpTool.get(imgUrl);
        }

        return bytes;
    }

    @Override
    protected void onPostExecute(byte[] bytes) {
        if (bytes != null) {
            //TODO 更新文件缓存
            FileCache fileCache = FileCache.getInstance();
            fileCache.putContent(imgUrl, bytes);

            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

            //TODO 更新内存缓存
            ImageCache imageCache = ImageCache.getInstance();
            imageCache.putImage(imgUrl, bitmap);

            if (imageView != null) {
                Object tag = imageView.getTag();
                if (tag != null && tag instanceof String) {
                    String sTag = (String) tag;

                    if (sTag.equals(imgUrl)) {
                        imageView.setImageBitmap(bitmap);
                    }
                }

            }
        }
    }
}
